//
//  TQVc.swift
//  GjCup
//
//  Created by abc on 2024/4/12.
//

import UIKit

class TQVc: UIViewController {
    
    
    @IBOutlet weak var typeBtn: UIButton!{
        didSet{
            typeBtn.layer.cornerRadius = 12
        }
    }
    lazy var models = [TQModel]()
    var type = 1{
        didSet{
            data()
        }
    }
    
    @IBOutlet weak var tv: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        data()
    }
    func data() {
        models.removeAll()
        AF.request("http://apis.juhe.cn/fapigx/mingyan/query?typeid=\(type)&key=62605634030e727e5054c6528e111153", method: .get).response {[weak self] response in
                print(response.request ?? "")  // original URL request
                print(response.response ?? "") // URL response
                print(response.data ?? "")     // server data
            print(response.result )   // result of response serialization
            if response.result.isSuccess {
                guard let data = response.data,
                      let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any]
                else { return  }
                if let result = json["result"] as? [String: Any],let realtime = result["list"] as? [[String: Any]] {
                    for i in realtime{
                        let m = TQModel()
                        m.setValuesForKeys(i)
                        self?.models.append(m)
                    }
                    self?.tv.reloadData()
                }
            }

        }



    }

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        let vc = segue.destination as! TQTypeVc
        vc.block = { [weak self](type, index) in
            self?.typeBtn.setTitle(type, for: .normal)
            self?.type = index
            
        }
        
    }
    

}
extension TQVc: UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TQListCell", for: indexPath) as! TQListCell
        let m = models[indexPath.row]
        cell.model = m
        return cell
        
    }
}
